﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Riel_Gestion.printer;
using log4net;
using Riel_Gestion.dao;
using Riel_Gestion.entities;

namespace Riel_Gestion
{
    public partial class FrmCompra : Form
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(FrmCompra));
        Decimal saldoAnt = 0;
        int filasAct = 0;

        public FrmCompra()
        {
            InitializeComponent();
        }

        private void cOMPRABindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            logger.Info("Guardando compra...");
            this.Validate();
            this.cOMPRABindingSource.EndEdit();
            
            int res = this.tableAdapterManager.UpdateAll(this.rielDataSet);

            if (res > 0)
            {
                logger.Info("Compra guardar exitosamente");
                MessageBox.Show("Compra guardada exitosamente", "Guardar Compra", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            if (res == 0)
            {
                logger.Info("No hay cambios para guardar");
                MessageBox.Show("No hay cambios para guardar", "Guardar Compra", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            if (res < 0)
            {
                logger.Error("Error al guardar compra");
                MessageBox.Show("Error al guardar compra", "Guardar Compra", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            filasAct = cOMPRADataGridView.RowCount;
        }

        private void FrmCompra_Load(object sender, EventArgs e)
        {
            logger.Info("Cargando tabla de Compras");
            cOMPRATableAdapter.FillByDate(rielDataSet.COMPRA, DateTime.Now.Date);

            filasAct = cOMPRADataGridView.RowCount;
        }

        private void btnAceptar_Click(object sender, EventArgs e)
        {

            if (filasAct != cOMPRADataGridView.RowCount)
                if (FrmMain.showInfoYesNoDialog("¿Desea guardar los cambios?", "Compras") == DialogResult.Yes)
                    cOMPRABindingNavigatorSaveItem_Click(sender, e);

            this.Close();
        }

        private void cOMPRADataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex == cOMPRADataGridView.Rows.Count - 1)
                cOMPRADataGridView.Rows[e.RowIndex].Cells[0].Value = DateTime.Now.Date;
        }

        private void btnImprimir_Click(object sender, EventArgs e)
        {
            logger.Info("Se envía a imprimir la tabla de Compras");
            PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();                     
            PrinterImpl printer = new PrinterImpl(cOMPRADataGridView, "Compras del " + String.Format("{0:dd/MM/yyyy}", DateTime.Now));
            
            printPreviewDialog.Document = printer.getDocument();
            if (printPreviewDialog.ShowDialog() == DialogResult.OK)
            {
                logger.Debug("Imprimiendo...");
                printer.print();
            }
        }

        private void cOMPRADataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                if (!cOMPRADataGridView.Rows[e.RowIndex].Cells[1].Value.ToString().Equals(""))
                {

                    rielDataSetTableAdapters.PROVEEDORESTableAdapter proveed = new Riel_Gestion.rielDataSetTableAdapters.PROVEEDORESTableAdapter();
                    int res = proveed.FillByCodProv(rielDataSet.PROVEEDORES, int.Parse(cOMPRADataGridView.Rows[e.RowIndex].Cells[1].Value.ToString()));
                                      
                    if (res != 0)
                    {
                        DTOSaldo saldos = CompraDAO.getSaldosTotalesById(cOMPRADataGridView.Rows[e.RowIndex].Cells[1].Value.ToString());
                        cOMPRADataGridView.Rows[e.RowIndex].Cells[5].Value = saldos.TotSaldo;
                        saldoAnt = saldos.TotSaldo;
                    }
                    else
                    {
                        FrmMain.showErrorDialog("El proveedor ingresado no existe.");
                    }
                }
            }

            if (e.ColumnIndex == 3)
            {
                if ("".Equals(cOMPRADataGridView.Rows[e.RowIndex].Cells[3].Value.ToString()))
                    cOMPRADataGridView.Rows[e.RowIndex].Cells[3].Value = 0;

                if ("".Equals(cOMPRADataGridView.Rows[e.RowIndex].Cells[4].Value.ToString()))
                    cOMPRADataGridView.Rows[e.RowIndex].Cells[4].Value = 0;

                cOMPRADataGridView.Rows[e.RowIndex].Cells[5].Value = saldoAnt + Decimal.Parse(cOMPRADataGridView.Rows[e.RowIndex].Cells[3].Value.ToString()) - Decimal.Parse(cOMPRADataGridView.Rows[e.RowIndex].Cells[4].Value.ToString());
            }

            if (e.ColumnIndex == 4)
            {
                if ("".Equals(cOMPRADataGridView.Rows[e.RowIndex].Cells[3].Value.ToString()))
                    cOMPRADataGridView.Rows[e.RowIndex].Cells[3].Value = 0;

                if ("".Equals(cOMPRADataGridView.Rows[e.RowIndex].Cells[4].Value.ToString()))
                    cOMPRADataGridView.Rows[e.RowIndex].Cells[4].Value = 0;

                cOMPRADataGridView.Rows[e.RowIndex].Cells[5].Value = saldoAnt + Decimal.Parse(cOMPRADataGridView.Rows[e.RowIndex].Cells[3].Value.ToString()) - Decimal.Parse(cOMPRADataGridView.Rows[e.RowIndex].Cells[4].Value.ToString());
            }
        }
    }
}
